//
//  DTPaginationViewModel.swift
//  Architecture
//
//  Created by tianXin on 2017/9/14.
//  Copyright © 2017年 田鑫. All rights reserved.
//

import UIKit
import MJRefresh

class DTPaginationViewModel: DTViewModelClass {

      var PaginationVC: DTPaginationViewController!
      var dataList         = [Any]()
      var page             = DTPage()

      init(_ vc: DTPaginationViewController) {
        PaginationVC = vc;
        super.init()
      }
      
      // MARK: - Refresh Method
      func loadData() {
       
      }
      //请求分页数据
      func requestPageData() {
        
      }
      //添加下拉刷新
      func addHeadRefresh() {
        let headRefresh = MJRefreshNormalHeader {
          self.headerRefreshing(sender: nil)
        }
        PaginationVC.refreshTableView.mj_header = headRefresh
      }
      //添加上托加载更多
      func addFooterRefresh() {
        let footRefresh = MJRefreshAutoNormalFooter{
          self.footRefreshing(sender: nil)
        }
        PaginationVC.refreshTableView.mj_footer = footRefresh
      }
      //刷新
      @objc func headerRefreshing(sender :Any?) {
        beforeStartRefresh()
        page.pageIndex = 1
        requestPageIndex(page.pageIndex, refreshType: .header)
      }
      //加载更多
      @objc func footRefreshing(sender :Any?) {
        beforeStartRefresh()
        requestPageIndex(page.pageIndex, refreshType: .footer)
      }  //结束刷新
      func endRefreshingWithType( refreshType: RefreshType)  {
        if refreshType == .header {
          PaginationVC.refreshTableView.mj_header.endRefreshing()
        }else{
          PaginationVC.refreshTableView.mj_footer.endRefreshing()
        }
      }
      //子类需要重写这个方法
      func requestPageIndex(_ pageIndex:Int, refreshType:RefreshType) {
        loadPageIndex(pageIndex, requestType: refreshType)
      }
      /**
       *  加载分页, 该方法需要子类重写，此方法废弃。使用requestPageIndex
       *
       *  @param pageIndex 当前分页索引
       *  @param requestType 请求类型
       */
      func loadPageIndex(_ pageIndex:Int,requestType:RefreshType) {
        
      }
      /**
       *  添加数据前调用，处理下拉和加载更多的结束后的动作
       *
       *  @param refreshType 刷新类型
       *  @param myDataList  添加数据
       */
      func addDataBeforeWithRefreshType(_ refreshType:RefreshType,dataArray: [Any])  {
        if refreshType == .header  {
          dataList.removeAll()
          if dataArray.count >= page.pageSize {
            page.addPageIndex()
            addFooterRefresh()
          }else{
            PaginationVC.refreshTableView.mj_footer = nil
          }
        }else{
          page.addPageIndex()
          if dataArray.count < page.pageSize {
            PaginationVC.refreshTableView.mj_footer = nil
          }
        }
      }
      func beforeStartRefresh() {
        
      }
}
